<template>
  <!-- 聊天输入容器 -->
  <div class="chat-input-container">
    <!-- 输入框和按钮的组合 -->
    <div class="input-wrapper">
      <!-- 添加文件上传区域 -->


      <el-input
        v-model="messageText"
        type="textarea"
        :autosize="{ minRows: 1, maxRows: 2 }"
        :placeholder="placeholder"
        resize="none"
        @keydown="handleKeydown"
        @keydown.enter.exact.prevent="handleSend"
        @keydown.enter.shift.exact="newline"
        @input="adjustHeight"
        ref="inputRef"
      />
      
      <div class="button-group">
        <!-- 新增带参数的发送按钮（Ctrl+Enter触发） -->
        <el-button
          :loading="loading"
          @click="handleSendWithParam"
          v-if="props.buttonColor !== '#f4ba40'"
        >
          <template #icon>
            <el-icon><CircleCheckFilled /></el-icon>
          </template>
          记录
        </el-button>
        <el-button
          type="primary"
          :loading="loading"
          @click="handleSend"
          :style="{ backgroundColor: props.buttonColor,
                    borderColor: props.buttonColor
           }"
        >
          <template #icon>
            <el-icon><Position /></el-icon>
          </template>
          发送
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Delete, Position, Upload, Plus, Document } from '@element-plus/icons-vue'
import { useChatStore } from '../stores/chat'
import { ElMessageBox,ElMessage } from 'element-plus'
import { CircleCheckFilled } from '@element-plus/icons-vue' // 新增图标




const handleSendWithParam = async () => {
  const content = messageText.value.trim()
  if (!content) return
  if (props.loading) return

  try {
    // 新增：传递参数到父组件
    emit('send', content, { is_records: 1 })
    messageText.value = ''
  } catch (error) {
    console.error('发送失败:', error)
    ElMessage.error('发送失败，请重试')
  }
}

// 添加快捷键监听
const handleKeydown = (e) => {
  if (e.key === 'Enter') {
    if (e.ctrlKey) {
      handleSendWithParam()
    } else if (!e.shiftKey) {
      handleSend()
    }
  }
}



// 定义组件的属性
const props = defineProps({
  loading: {
    type: Boolean,
    default: false
  },
  buttonColor: {
    type: String,
    default: '#0132fe' // 默认颜色
  }

})

// 定义组件的事件
const emit = defineEmits(['send', 'clear'])

// 使用聊天存储
const chatStore = useChatStore()
// 消息文本的响应式引用
const messageText = ref('')

// 输入框的占位符
const placeholder = `请输入消息`

// 计算属性，用于获取聊天存储中的Token计数
const tokenCount = computed(() => chatStore.tokenCount)

const handleSend = async () => {
  const content = messageText.value.trim()
  if (!content) return
  if (props.loading) return
  
  try {
    emit('send', content)
    messageText.value = ''
  } catch (error) {
    console.error('发送失败:', error)
    ElMessage.error('发送失败，请重试')
  }
}



// 处理换行的函数
const newline = (e) => {
  // 在消息文本中添加换行符
  messageText.value += '\n'
}

// 处理清空对话的函数
const handleClear = async () => {
  try {
    // 使用Element Plus的消息框组件，提示用户是否确定清空对话记录
    await ElMessageBox.confirm(
      '确定要清空所有对话记录吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    // 如果用户确认清空，则触发clear事件
    emit('clear')
  } catch {
    // 如果用户取消操作，则不做任何事情
  }
}

const inputRef = ref(null)

// 调整输入框高度的方法
const adjustHeight = () => {
  if (inputRef.value) {
    // 获取输入框的DOM元素,因为是 ref，需要通过$el获取DOM元素
    const textarea = inputRef.value.$el.querySelector('textarea')
    if (textarea) {
      textarea.style.height = 'auto'
      textarea.style.height = `${textarea.scrollHeight}px`
    }
  }
}

</script>

<style lang="scss" scoped>


// 聊天输入容器的样式
.chat-input-container {
  padding: 1rem;
  background-color: var(--bg-color);
  border-top: 1px solid var(--border-color);
  // 输入框和按钮组合的样式
  .input-wrapper {
    display: flex;
    gap: 1rem;
    margin-bottom: 0.5rem;
    
    .el-input {
      flex: 1;
      height: 28px;
      
      :deep(.el-textarea__inner) {
        transition: all 0.3s;
        line-height: 1.5;
        // padding: 16px 18px;
        overflow-y: auto;
        white-space: pre-wrap; //允许换行
        word-wrap: break-word; //长单词换行
        min-height: 28px;
      }
    }
  }

  :deep(.el-button--primary) {
    --el-button-bg-color: #0132fe !important; // 修改颜色值
    --el-button-border-color: #0132fe !important;
    --el-button-text-color: white; // 文字颜色
  }
}



// 按钮组的样式
.button-group {
  display: flex;
  // gap: 0.5rem;
  gap: 0; // 缩小间距
  align-items: flex-end;
}
.el-button {
    border-radius: 16px !important; // ✅ 按钮圆角
    padding: 12px 20px; // 调整按钮内边距
    
  }
:deep(.el-input) {
  .el-input__wrapper {
    border-radius: 16px;
  }
}


.upload-area {
  margin-bottom: 1rem;
  padding: 1rem;
  border: 2px dashed var(--border-color);
  border-radius: var(--border-radius);
  
  .preview-list {
    display: flex;
    flex-wrap: wrap;
    gap: 1rem;
    margin-top: 1rem;
    
    .preview-item {
      position: relative;
      width: 100px;
      height: 100px;
      
      .preview-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
        border-radius: var(--border-radius);
      }
      
      .file-preview {
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        background-color: var(--bg-color-secondary);
        border-radius: var(--border-radius);
        
        .el-icon {
          font-size: 2rem;
          margin-bottom: 0.5rem;
          color: white;
        }
        
        span {
          font-size: 0.8rem;
          text-align: center;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          width: 90%;
        }
      }
      
      .delete-btn {
        position: absolute;
        top: -0.5rem;
        right: -0.5rem;
        padding: 0.25rem;
        transform: scale(0.8);
      }
    }
  }
}
</style>